<template>
    <div class="payDrug-view">

      <modules-title titleName="直接售药">

        <template slot="other">
          <div class="priceView">
            <div class="priceView-item">
              <span>总金额：¥{{total.toFixed(2)}}</span>
            </div>

            <div class="priceView-item">
              <span>优惠 ¥</span>
              <el-input ref="saleInput" v-model="preferentialValue" @keyup.native="proving" placeholder="请输入" @input="inputChange" @blur="inputBlur"></el-input>
            </div>

            <div class="priceView-item">
              <span>应收：</span>
              <span class="price">¥{{amount.toFixed(2)}}</span>
            </div>
          </div>
        </template>
        <template slot="btn">
          <el-button class="main-btn" type="primary" @click="payClick">收费</el-button>

          <el-checkbox v-model="checked" @change="checkChange">打印小票</el-checkbox>
        </template>
      </modules-title>

      <div class="scroll-view">
        <information-data ref="infomation"></information-data>

        <div class="drug-view">
          <drug-tab ref="drugTab" @total-change="totalChange" @delete="deleteClick"></drug-tab>
        </div>
      </div>

      <pay-dialog ref="payDialog" @pay-confirm="payConfirm"></pay-dialog>

      <print ref="print"></print>
    </div>
</template>

<script>
  import print from "../../print/print";
  import {getDrugsList} from "../../../api/drugsManagement";
  import {medicine} from "../../../api/payOrDrug";
  import payDialog from "../modules/payDialog";
  import informationData from "../modules/informationData";
  import drugTab from "../modules/drugTab";

    export default {
        name: "index",
        components:{informationData,drugTab,payDialog,print},
        data:function () {
            return{
                preferentialValue:'',
                checked:false,
                total:0,
                sale:0,
            }
        },
        computed: {
            amount: function(){//test为计算属性，调用时和调用属性一样调用test即可
                let am = 0;
                am = this.total - this.preferentialValue;
                return am//msg是依赖属性，改变时会执行test函数
            }
        },
        mounted:function(){
            getDrugsList().then()
            this.checked = this.$store.getters.billCheck
        },
        beforeRouteLeave(to, from, next) {
            // if (this.count > 1) {
            //     this.$confirm('有内容未保存, 是否确定离开此页面?', '提示', {
            //         confirmButtonText: '确定',
            //         cancelButtonText: '取消',
            //         type: 'warning'
            //     }).then(() => {
            //         next()
            //     }).catch(() => {
            //         next(false)
            //     });
            // } else {
            //     next()
            // }
            next()
        },
        methods:{
            checkChange:function(){
                console.log(this.checked)
                this.$store.dispatch("setting/setBillCheck",this.checked)
            },
            deleteClick:function(){
                this.preferentialValue = 0;
            },
            updateApi:function () {
                console.log("updateApi")

            },
            payClick:function () {

                let info = this.$refs.infomation.validate();
                if (!info){
                    return;
                }
                let prescription = this.$refs.drugTab.validate();
                if (!prescription){
                    return;
                }
                if (this.amount<=0){
                    this.$message.error("实收金额不能为0");
                    return;
                }
                info.details = prescription;
                this.$set(info,"total_amount",this.total)
                this.$set(info,"receipts_amount",this.amount)
                console.log(info);
                this.$refs.payDialog.openDialog(info);
            },
            totalChange:function (total) {
                this.total = total;
            },
            inputChange:function (value) {
                // console.log(value)
                // if (value > this.total){
                //     this.preferentialValue = this.total
                // }
            },
            inputBlur:function(){
                this.preferentialValue = Number(this.preferentialValue).toFixed(2)
            },
            payConfirm:function(data){
                let status = 1;
                if (this.$store.getters.systemSetting.dic_value){
                    let obj = JSON.parse(this.$store.getters.systemSetting.dic_value);
                    status = Number(!obj.charge_dispensing_management.function_set)
                }
                data.status = status;
                const loading = this.$loading({
                    lock: true,
                    text: 'Waiting',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                medicine(data).then((res)=>{
                    loading.close();
                    if (res.code == 200){
                        this.$message({
                            message: '售药成功',
                            type: 'success'
                        });
                        this.total = 0;
                        this.preferentialValue = 0;
                        this.$refs.drugTab.clearData()
                        this.$refs.infomation.clearData()
                        if (this.checked){
                            let printData = {
                                prescription_ary_info:[{details:data.details}],
                                check_item:[],
                                surcharge:[],
                                amount:data.total_amount,
                                receipts_amount:data.receipts_amount,
                                created_at:this.dealDate(new Date()),
                                user_name:this.$store.getters.userInfo.real_name,
                            }
                            this.$refs.print.printBill(printData);
                        }
                    }else {
                        this.$message.error(res.msg);
                    }
                }).catch((err)=>{
                    loading.close();
                })
            },
            dealDate:function (date) {
                let year = date.getFullYear();
                let month = date.getMonth() + 1;
                let day = date.getDate();
                if (month < 10){
                    month = "0" + month
                }
                if (day < 10){
                    day = "0" + day;
                }

                let hour = date.getHours();
                let minute = date.getMinutes();
                let second = date.getSeconds();

                if (minute < 10){
                    minute = "0" + minute
                }

                if (second < 10){
                    second = "0" + second
                }

                return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
            },
            proving:function() {
                let str = this.preferentialValue
                // this.form.skus[e].Price 是input的值　　
                // 先把非数字的都替换掉，除了数字和.
                str = str.replace(/[^\d.]/g, '');
                // 必须保证第一个为数字而不是.
                str = str.replace(/^\./g, '');
                // 保证只有出现一个.而没有多个.
                str = str.replace(/\.{2,}/g, '');
                // 保证.只出现一次，而不能出现两次以上
                str = str.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
                let index = -1
                for (let i in str) {
                    if (str[i] === '.') {
                        index = i
                    }
                    if (index !== -1) {
                        if (i - index > 2) {
                            str = str.substring(0, str.length - 1)
                        }
                    }
                }
                if (Number(str) > this.total){
                    str = this.total
                }
                this.preferentialValue = str;

            },
        }
    }
</script>

<style lang="scss" scoped>
  @import "@/assets/scss/payOrDrug/payDrug.scss";
</style>
